/*
 * Textur.cpp
 *
 *  Created on: Feb 15, 2011
 *      Author: alki
 */

#include "Textur.h"
#include "../Exception.h"

Textur::Textur() {
	this->m_textur = NULL;
}

Textur::~Textur() {
	if(this->m_textur!=NULL) {
		SDL_FreeSurface(this->m_textur);
		this->m_textur = NULL;
	}
}

void Textur::Load(string file) {
	if(this->m_textur!=NULL) {
		throw new Exception(NULL,__FILE__,__LINE__,"Fehler beim Laden der Textur","Surface schon geladen!");
	}

	this->m_textur = IMG_Load(file.c_str());
	if(!this->m_textur) {
		throw new Exception(NULL,__FILE__,__LINE__,"Fehler beim Laden der Textur","Datei nicht gefunden");
	}
}

FARBE Textur::getPixel(float u,float v) const {
	int x=this->m_textur->w*u;
	int y=this->m_textur->h*v;
	Uint32 farbe=this->getPixel(x,y);

	FARBE ret;
	ret.r=((float)((farbe&0xFF0000)>>16))/256;
	ret.g=((float)((farbe&0xFF00)>>8))/256;
	ret.b=((float)((farbe&0xFF)))/256;

	return ret;
}

Uint32 Textur::getPixel(int x, int y) const {
	int bpp = this->m_textur->format->BytesPerPixel;
	Uint8 *p = (Uint8 *)this->m_textur->pixels + y * this->m_textur->pitch + x * bpp;

	switch(bpp) {
	case 1: {
		return *p;
	} break;
	case 2: {
		return *(Uint16 *)p;
	} break;
	case 3: {
		if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
			return p[0] << 16 | p[1] << 8 | p[2];
		else
			return p[0] | p[1] << 8 | p[2] << 16;
	} break;
	case 4: {
		return *(Uint32 *)p;
	} break;
	}

	return 0;
}
